package com.zzedu.manager.impl;

import com.google.common.collect.Lists;
import com.zzedu.domain.ZzUploadFile;
import com.zzedu.integration.oss.IOssClientService;
import com.zzedu.manager.IZzUploadFileManager;
import com.zzedu.service.IZzUploadFileService;
import com.zzedu.vo.ZzUploadFileVO;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class ZzUploadFileManagerImpl implements IZzUploadFileManager {

    private static final Logger logger = LoggerFactory.getLogger(ZzUploadFileManagerImpl.class);

    @Autowired
    IZzUploadFileService zzUploadFileService;

    @Autowired
    IOssClientService ossClientService;

    /**
     * 根据 ID 获取文件信息
     */
    @Override
    public ZzUploadFileVO getById(Long id) {
        return toUploadFileVO(zzUploadFileService.getById(id));
    }

    /**
     * 根据 ID 列表获取文件信息
     */
    @Override
    public List<ZzUploadFileVO> getByIdList(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return Lists.newArrayList();
        }
        return Optional.ofNullable(zzUploadFileService.listByIds(ids)).orElse(Lists.newArrayList()).stream().map(this::toUploadFileVO).collect(Collectors.toList());
    }

    /**
     * 根据 ID 列表获取文件信息 Map
     */
    @Override
    public Map<Long, ZzUploadFileVO> getMapByIdList(List<Long> ids) {
        return Optional.ofNullable(getByIdList(ids)).orElse(Lists.newArrayList())
                .stream().collect(Collectors.toMap(ZzUploadFileVO::getId, Function.identity()));
    }

    /**
     * 转换为 VO
     */
    private ZzUploadFileVO toUploadFileVO(ZzUploadFile file) {
        ZzUploadFileVO vo = new ZzUploadFileVO();
        vo.setId(file.getId());
        vo.setSize(file.getSize());
        vo.setFileExt(file.getFileExt());
        vo.setUrl(ossClientService.convertURL(file.getUrl()));
        return vo;
    }
}
